package com.map;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class UserLogFilter implements Filter {
	private String logFilePath;
	private static Set<String> userCookiIDs = new HashSet<String>();

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {
		if(! (request instanceof HttpServletRequest)){
			chain.doFilter(request, response);
			return;
		}
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		if(UserLogFilter.userCookiIDs.contains(httpRequest.getSession().getId())){
			chain.doFilter(request, response);
			return;
		}
		UserLogFilter.userCookiIDs.add(httpRequest.getSession().getId());
		File file = new File(this.logFilePath);
		if(!file.exists()){
			file.createNewFile();
		}
		FileWriter writer = new FileWriter(file,true);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		StringBuffer log = new StringBuffer();
		log.append("time: "+format.format(new Date())+"\n");
		log.append("User-Agent: "+httpRequest.getHeader("User-Agent")+"\n");
		log.append("IP: "+httpRequest.getRemoteAddr()+"\n");
		writer.write(log.toString());
		writer.flush();
		writer.close();
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		logFilePath = arg0.getInitParameter("logfilepath");
	}

}
